package org.jeecg.modules.oms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.oms.entity.DesignFile;
import org.jeecg.modules.oms.entity.ProductSalesOrder;
import org.jeecg.modules.oms.entity.ProductSalesOrderDetail;
import org.jeecg.modules.oms.entity.ProductSalesOrderProgress;
import org.jeecg.modules.oms.entity.ProductSalesOrderTransaction;
import org.jeecg.modules.oms.mapper.ProductSalesOrderDetailMapper;
import org.jeecg.modules.oms.mapper.ProductSalesOrderMapper;
import org.jeecg.modules.oms.service.*;
import org.jeecg.modules.oms.vo.ProductSalesOrderPageVO;
import org.jeecg.modules.oms.vo.ProductSalesOrderVO;
import org.jeecg.modules.system.entity.SysEmployee;
import org.jeecg.modules.system.service.ISysEmployeeService;
import org.jeecg.modules.oms.entity.CfAccessoriesTable;
import org.jeecg.modules.oms.entity.CfProfileMaterial;
import org.jeecg.modules.oms.entity.XgeAccessoriesTable;
import org.jeecg.modules.oms.entity.XingeProfileMaterial;
import org.jeecg.modules.oms.service.ICfAccessoriesTableService;
import org.jeecg.modules.oms.service.ICfProfileMaterialService;
import org.jeecg.modules.oms.service.IXgeAccessoriesTableService;
import org.jeecg.modules.oms.service.IXingeProfileMaterialService;
import org.jeecg.modules.oms.vo.WmsRequisitionVO;
import org.jeecg.modules.oms.vo.WmsRequisitionProfileVO;
import org.jeecg.modules.oms.vo.WmsRequisitionAccessoryVO;
import org.jeecg.modules.oms.mapper.WmsRequisitionVOMapper;
import org.jeecg.modules.oms.mapper.WmsRequisitionProfileVOMapper;
import org.jeecg.modules.oms.mapper.WmsRequisitionAccessoryVOMapper;
import org.jeecg.common.event.EventPublisher;
import org.jeecg.common.event.RequisitionOutboundEvent;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Base64;
import java.nio.charset.StandardCharsets;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 成品销售订单服务实现类
 */
@Slf4j
@Service
public class ProductSalesOrderServiceImpl extends ServiceImpl<ProductSalesOrderMapper, ProductSalesOrder> implements IProductSalesOrderService {

    @Autowired
    private IProductSalesOrderDetailService productSalesOrderDetailService;
    
    @Autowired
    private IProductSalesOrderTransactionService productSalesOrderTransactionService;
    
    @Autowired
    private IProductSalesOrderProgressService productSalesOrderProgressService;
    
    @Autowired
    private ProductSalesOrderDetailMapper orderDetailMapper;
    
    @Autowired
    private IDesignFileService designFileService;

    @Autowired
    private ISysEmployeeService employeeService;

    @Autowired
    private IXgeAccessoriesTableService accessoriesTableService;

    @Autowired
    private IXgeGlassSizeTableService glassSizeTableService;

    @Autowired
    private IXgeProfileSizeTableService profileSizeTableService;

    @Autowired
    private IXingeProfileMaterialService xingeProfileMaterialService;

    @Autowired
    private IXingeProfileCutDetailService xingeProfileCutDetailService;

    @Autowired
    private ICfProfileMaterialService cfProfileMaterialService;

    @Autowired
    private ICfProfileCutDetailService cfProfileCutDetailService;

    @Autowired
    private ICfProfileWorkDetailService cfProfileWorkDetailService;

    @Autowired
    private ICfAccessoriesTableService cfAccessoriesTableService;

    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private WmsRequisitionVOMapper wmsRequisitionVOMapper;
    
    @Autowired
    private WmsRequisitionProfileVOMapper wmsRequisitionProfileVOMapper;
    
    @Autowired
    private WmsRequisitionAccessoryVOMapper wmsRequisitionAccessoryVOMapper;

    @Autowired
    private EventPublisher eventPublisher;

    @Override
    public IPage<ProductSalesOrder> getProductSalesOrderPageList(Page<ProductSalesOrder> page, ProductSalesOrderPageVO productSalesOrderPageVO) {
        return baseMapper.getProductSalesOrderPageList(page, productSalesOrderPageVO);
    }
    
    @Override
    public ProductSalesOrderVO getProductSalesOrderById(String id) {
        // 查询订单信息
        ProductSalesOrder productSalesOrder = getById(id);
        if (productSalesOrder == null) {
            return null;
        }
        
        // 查询订单明细
        List<ProductSalesOrderDetail> detailList = productSalesOrderDetailService.getDetailListByOrderId(id);
        
        // 封装VO
        ProductSalesOrderVO productSalesOrderVO = new ProductSalesOrderVO();
        BeanUtils.copyProperties(productSalesOrder, productSalesOrderVO);
        productSalesOrderVO.setProductSalesOrderDetailList(detailList);
        
        return productSalesOrderVO;
    }
    
    @Override
    public ProductSalesOrder getProductSalesOrderByOrderNo(String orderNo) {
        return baseMapper.getProductSalesOrderByOrderNo(orderNo);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addProductSalesOrder(ProductSalesOrderVO productSalesOrderVO) {
        // 设置初始状态
        productSalesOrderVO.setStatus(0); // 新增订单-待审核
        
        // 生成订单编号
        if (StringUtils.isBlank(productSalesOrderVO.getOrderNo())) {
            productSalesOrderVO.setOrderNo(generateOrderNo());
        }
        
        // 计算金额
        calculateAmount(productSalesOrderVO);
        
        // 初始化付款相关字段
        BigDecimal totalAmount = productSalesOrderVO.getTotalAmount() != null ? productSalesOrderVO.getTotalAmount() : BigDecimal.ZERO;
        BigDecimal paidAmount = productSalesOrderVO.getPaidAmount() != null ? productSalesOrderVO.getPaidAmount() : BigDecimal.ZERO;
        BigDecimal unPaidAmount = productSalesOrderVO.getUnpaidAmount() != null ? productSalesOrderVO.getUnpaidAmount() : BigDecimal.ZERO;
        
        // 设置已付款金额和未付款金额
        productSalesOrderVO.setPaidAmount(paidAmount);
        productSalesOrderVO.setUnpaidAmount(totalAmount.subtract(unPaidAmount));
        
        // 设置付款状态
        if (paidAmount.compareTo(BigDecimal.ZERO) == 0) {
            // 未付款
            productSalesOrderVO.setPayStatus(0);
        } else if (unPaidAmount.compareTo(BigDecimal.ZERO) == 0) {
            // 已付清
            productSalesOrderVO.setPayStatus(2);
        } else {
            // 部分付款
            productSalesOrderVO.setPayStatus(1);
        }
        //获取当前用户的优化软件类型 设置订单优化类型
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // 获取当前登录用户信息，用于设置交易记录的创建人和交易人员
        SysEmployee employee = employeeService.getById(loginUser.getId());
        productSalesOrderVO.setOptimizationSoftwareType(employee.getOptimizeSoftType());
        productSalesOrderVO.setWindowDoorType(employee.getWindowDoorType());
        
        // 保存订单
        boolean result = save(productSalesOrderVO);
        if (!result) {
            throw new JeecgBootException("保存订单失败");
        }
        
        // 保存订单明细
        List<ProductSalesOrderDetail> detailList = productSalesOrderVO.getProductSalesOrderDetailList();
        if (detailList != null && !detailList.isEmpty()) {
            result = productSalesOrderDetailService.saveOrderDetailBatch(productSalesOrderVO.getId(), detailList);
            if (!result) {
                throw new JeecgBootException("保存订单明细失败");
            }
        }

        // 优先处理transactionList - 优先使用前端传递的交易记录列表
        if (productSalesOrderVO.getTransactionList() != null && !productSalesOrderVO.getTransactionList().isEmpty()) {
            List<ProductSalesOrderTransaction> transactionList = productSalesOrderVO.getTransactionList();
            
            log.info("处理订单[{}]的交易记录列表，共{}条记录", productSalesOrderVO.getOrderNo(), transactionList.size());
            
            // 处理每条交易记录
            for (ProductSalesOrderTransaction transaction : transactionList) {
                // 设置订单ID
                transaction.setOrderId(productSalesOrderVO.getId());
                
                // 如果没有设置交易时间，则使用当前时间
                if (transaction.getTransactionTime() == null) {
                    transaction.setTransactionTime(new Date());
                }
                
                // 如果没有设置描述，则根据交易类型设置默认描述
                if (StringUtils.isBlank(transaction.getDescription())) {
                    setDefaultTransactionDescription(transaction);
                }
                
                // 设置创建人和交易人员
                if (loginUser != null) {
                    if (StringUtils.isBlank(transaction.getTransactionPersonId())) {
                        transaction.setTransactionPersonId(loginUser.getId());
                    }
                    if (StringUtils.isBlank(transaction.getCreateBy())) {
                        transaction.setCreateBy(loginUser.getUsername());
                    }
                }
                
                // 保存交易记录
                productSalesOrderTransactionService.addTransaction(transaction);
            }
            
            // 更新订单的已付款金额和付款状态
            updateOrderPaidAmount(productSalesOrderVO);
        }
        // 处理单个transaction对象 - 如果没有交易记录列表，但有单个交易记录
        else if (productSalesOrderVO.getTransaction() != null) {
            ProductSalesOrderTransaction transaction = productSalesOrderVO.getTransaction();
            transaction.setOrderId(productSalesOrderVO.getId());
            
            log.info("处理订单[{}]的单个交易记录", productSalesOrderVO.getOrderNo());
            
            // 如果没有设置交易时间，则使用当前时间
            if (transaction.getTransactionTime() == null) {
                transaction.setTransactionTime(new Date());
            }
            
            // 如果没有设置描述，则根据交易类型设置默认描述
            if (StringUtils.isBlank(transaction.getDescription())) {
                setDefaultTransactionDescription(transaction);
            }
            
            // 设置创建人和交易人员
            if (loginUser != null) {
                if (StringUtils.isBlank(transaction.getTransactionPersonId())) {
                    transaction.setTransactionPersonId(loginUser.getId());
                }
                if (StringUtils.isBlank(transaction.getCreateBy())) {
                    transaction.setCreateBy(loginUser.getUsername());
                }
            }
            
            // 保存交易记录
            productSalesOrderTransactionService.addTransaction(transaction);
            
            // 更新订单的已付款金额和付款状态
            updateOrderPaidAmount(productSalesOrderVO);
        }
        // 自动创建交易记录 - 如果有预付款和支付凭证，但没有提供交易记录
        else if (paidAmount.compareTo(BigDecimal.ZERO) > 0 && StringUtils.isNotBlank(productSalesOrderVO.getPaymentVoucher())) {
            ProductSalesOrderTransaction transaction = new ProductSalesOrderTransaction();
            transaction.setOrderId(productSalesOrderVO.getId());
            
            log.info("订单[{}]有预付款和支付凭证，自动创建交易记录", productSalesOrderVO.getOrderNo());
            
            // 使用前端传递的交易类型，如果没有则默认为预付款
            transaction.setTransactionType(productSalesOrderVO.getTransactionType() != null ? productSalesOrderVO.getTransactionType() : 1);
            
            transaction.setAmount(paidAmount);
            transaction.setTransactionTime(new Date());
            
            // 使用前端传递的支付方式，如果没有则默认为现金
            transaction.setPaymentMethod(productSalesOrderVO.getPaymentMethod() != null ? productSalesOrderVO.getPaymentMethod() : 1);
            transaction.setTransactionVoucher(productSalesOrderVO.getPaymentVoucher());
            transaction.setDescription("订单预付款");
            
            // 设置创建人和交易人员
            if (loginUser != null) {
                transaction.setTransactionPersonId(loginUser.getId());
                transaction.setCreateBy(loginUser.getUsername());
            }
            
            // 保存交易记录
            productSalesOrderTransactionService.addTransaction(transaction);
        }
        
        // 记录订单状态变更
        ProductSalesOrderProgress progress = new ProductSalesOrderProgress();
        progress.setOrderId(productSalesOrderVO.getId());
        progress.setNewStatus(0); // 新增订单-待审核
        progress.setChangeTime(new Date());
        
        // 获取当前登录用户
        if (loginUser != null) {
            progress.setOperatorId(loginUser.getId());
            progress.setOperatorName(loginUser.getRealname());
            progress.setChangeReason("新增订单");
        }
        
        productSalesOrderProgressService.addProgress(progress);
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean editProductSalesOrder(ProductSalesOrderVO productSalesOrderVO) {
        // 查询原订单信息
        ProductSalesOrder oldOrder = getById(productSalesOrderVO.getId());
        if (oldOrder == null) {
            return false;
        }
        
        // 检查订单状态，只有待审核状态才能修改
        if (oldOrder.getStatus() != 0) {
            return false;
        }
        
        // 计算金额
        calculateAmount(productSalesOrderVO);
        
        // 处理付款相关字段
        BigDecimal totalAmount = productSalesOrderVO.getTotalAmount() != null ? productSalesOrderVO.getTotalAmount() : BigDecimal.ZERO;
        BigDecimal prepayment = productSalesOrderVO.getPrepayment() != null ? productSalesOrderVO.getPrepayment() : BigDecimal.ZERO;
        BigDecimal oldPrepayment = oldOrder.getPrepayment() != null ? oldOrder.getPrepayment() : BigDecimal.ZERO;
        
        // 设置已付款金额和未付款金额
        productSalesOrderVO.setPaidAmount(prepayment);
        productSalesOrderVO.setUnpaidAmount(totalAmount.subtract(prepayment));
        
        // 设置付款状态
        if (prepayment.compareTo(BigDecimal.ZERO) == 0) {
            // 未付款
            productSalesOrderVO.setPayStatus(0);
        } else if (prepayment.compareTo(totalAmount) >= 0) {
            // 已付清
            productSalesOrderVO.setPayStatus(2);
        } else {
            // 部分付款
            productSalesOrderVO.setPayStatus(1);
        }
        
        // 更新订单
        boolean result = updateById(productSalesOrderVO);
        if (!result) {
            return false;
        }
        
        // 更新订单明细
        // 先删除原有明细
        productSalesOrderDetailService.deleteDetailByOrderId(productSalesOrderVO.getId());
        
        // 保存新明细
        List<ProductSalesOrderDetail> detailList = productSalesOrderVO.getProductSalesOrderDetailList();
        if (detailList != null && !detailList.isEmpty()) {
            result = productSalesOrderDetailService.saveOrderDetailBatch(productSalesOrderVO.getId(), detailList);
            if (!result) {
                return false;
            }
        }
        
        // 获取当前登录用户信息，用于设置交易记录的创建人和交易人员
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        
        // 优先处理transactionList - 优先使用前端传递的交易记录列表
        if (productSalesOrderVO.getTransactionList() != null && !productSalesOrderVO.getTransactionList().isEmpty()) {
            //先清除已有的交易记录
            productSalesOrderTransactionService.deleteTransactionByOrderId(productSalesOrderVO.getId());

            List<ProductSalesOrderTransaction> transactionList = productSalesOrderVO.getTransactionList();
            
            log.info("处理订单[{}]的交易记录列表，共{}条记录", productSalesOrderVO.getOrderNo(), transactionList.size());
            
            // 处理每条交易记录
            for (ProductSalesOrderTransaction transaction : transactionList) {
                // 设置订单ID
                transaction.setOrderId(productSalesOrderVO.getId());
                
                // 如果没有设置交易时间，则使用当前时间
                if (transaction.getTransactionTime() == null) {
                    transaction.setTransactionTime(new Date());
                }
                
                // 如果没有设置描述，则根据交易类型设置默认描述
                if (StringUtils.isBlank(transaction.getDescription())) {
                    setDefaultTransactionDescription(transaction);
                }
                
                // 设置创建人和交易人员
                if (loginUser != null) {
                    if (StringUtils.isBlank(transaction.getTransactionPersonId())) {
                        transaction.setTransactionPersonId(loginUser.getId());
                    }
                    if (StringUtils.isBlank(transaction.getCreateBy())) {
                        transaction.setCreateBy(loginUser.getUsername());
                    }
                }
                
                // 保存交易记录
                productSalesOrderTransactionService.addTransaction(transaction);
            }
            
            // 更新订单的已付款金额和付款状态
            updateOrderPaidAmount(productSalesOrderVO);
        }
        // 处理单个transaction对象 - 如果没有交易记录列表，但有单个交易记录
        else if (productSalesOrderVO.getTransaction() != null) {
            ProductSalesOrderTransaction transaction = productSalesOrderVO.getTransaction();
            transaction.setOrderId(productSalesOrderVO.getId());
            
            log.info("处理订单[{}]的单个交易记录", productSalesOrderVO.getOrderNo());
            
            // 如果没有设置交易时间，则使用当前时间
            if (transaction.getTransactionTime() == null) {
                transaction.setTransactionTime(new Date());
            }
            
            // 如果没有设置描述，则根据交易类型设置默认描述
            if (StringUtils.isBlank(transaction.getDescription())) {
                setDefaultTransactionDescription(transaction);
            }
            
            // 设置创建人和交易人员
            if (loginUser != null) {
                if (StringUtils.isBlank(transaction.getTransactionPersonId())) {
                    transaction.setTransactionPersonId(loginUser.getId());
                }
                if (StringUtils.isBlank(transaction.getCreateBy())) {
                    transaction.setCreateBy(loginUser.getUsername());
                }
            }
            
            // 保存交易记录
            productSalesOrderTransactionService.addTransaction(transaction);
            
            // 更新订单的已付款金额和付款状态
            updateOrderPaidAmount(productSalesOrderVO);
        }
        // 自动创建交易记录 - 如果预付款有增加且有支付凭证，则自动创建交易记录
        else if (prepayment.compareTo(oldPrepayment) > 0 && StringUtils.isNotBlank(productSalesOrderVO.getPaymentVoucher())) {
            // 只记录增加的部分
            BigDecimal increaseAmount = prepayment.subtract(oldPrepayment);
            
            ProductSalesOrderTransaction transaction = new ProductSalesOrderTransaction();
            transaction.setOrderId(productSalesOrderVO.getId());
            
            log.info("订单[{}]预付款增加{}，自动创建交易记录", productSalesOrderVO.getOrderNo(), increaseAmount);
            
            // 使用前端传递的交易类型，如果没有则默认为预付款
            transaction.setTransactionType(productSalesOrderVO.getTransactionType() != null ? productSalesOrderVO.getTransactionType() : 1);
            
            transaction.setAmount(increaseAmount);
            transaction.setTransactionTime(new Date());
            
            // 使用前端传递的支付方式，如果没有则默认为现金
            transaction.setPaymentMethod(productSalesOrderVO.getPaymentMethod() != null ? productSalesOrderVO.getPaymentMethod() : 1);
            transaction.setTransactionVoucher(productSalesOrderVO.getPaymentVoucher());
            transaction.setDescription("增加预付款");
            
            // 设置创建人和交易人员
            if (loginUser != null) {
                transaction.setTransactionPersonId(loginUser.getId());
                transaction.setCreateBy(loginUser.getUsername());
            }
            
            // 保存交易记录
            productSalesOrderTransactionService.addTransaction(transaction);
        }
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteProductSalesOrder(String id) {
        // 查询原订单信息
        ProductSalesOrder order = getById(id);
        if (order == null) {
            log.warn("尝试删除不存在的订单，ID: {}", id);
            return false;
        }
        
        log.info("开始删除订单: {}, 订单编号: {}", id, order.getOrderNo());
        
        try {
            // 删除订单明细 (会同时删除与明细关联的长风窗型确认文件数据)
            log.info("删除订单明细数据，订单ID: {}", id);
        productSalesOrderDetailService.deleteDetailByOrderId(id);
        
        // 删除交易记录
            log.info("删除订单交易记录，订单ID: {}", id);
        productSalesOrderTransactionService.deleteTransactionByOrderId(id);
        
        // 删除进度记录
            log.info("删除订单进度记录，订单ID: {}", id);
        productSalesOrderProgressService.deleteProgressByOrderId(id);
        
        // 删除订单
            log.info("删除订单主表记录，订单ID: {}", id);
            boolean result = removeById(id);
            
            if (result) {
                log.info("成功删除订单及所有关联数据，订单ID: {}, 订单编号: {}", id, order.getOrderNo());
            } else {
                log.error("删除订单主表记录失败，订单ID: {}", id);
            }
            
            return result;
        } catch (Exception e) {
            log.error("删除订单过程中发生异常，订单ID: {}", id, e);
            throw e;
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatchProductSalesOrder(String[] ids) {
        if (ids == null || ids.length == 0) {
            log.warn("批量删除订单时传入的ID为空");
            return false;
        }
        
        log.info("开始批量删除订单，共{}条记录", ids.length);
        
        boolean allSuccess = true;
        for (String id : ids) {
            boolean success = deleteProductSalesOrder(id);
            if (!success) {
                allSuccess = false;
                log.warn("批量删除订单时，订单ID: {} 删除失败", id);
            }
        }
        
        log.info("批量删除订单完成，结果: {}", allSuccess ? "全部成功" : "部分失败");
        return allSuccess;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrderStatus(String id, Integer oldStatus, Integer newStatus, String changePersonId,String changeReason) {
        // 查询原订单信息
        ProductSalesOrder order = getById(id);
        if (order == null) {
            return false;
        }
        
        // 检查状态是否匹配
        if (oldStatus != null && !oldStatus.equals(order.getStatus())) {
            return false;
        }
        
        // 记录状态变更
        ProductSalesOrderProgress progress = new ProductSalesOrderProgress();
        progress.setOrderId(id);
        progress.setOldStatus(oldStatus);
        progress.setNewStatus(newStatus);
        progress.setChangeTime(new Date());
        progress.setOperatorId(changePersonId);
        progress.setChangeReason(changeReason);
        
        return productSalesOrderProgressService.addProgress(progress);
    }
    
    @Override
    public String getMaxOrderNo() {
        return baseMapper.getMaxOrderNo();
    }
    
    @Override
    public String generateOrderNo() {
        // 生成订单编号规则：CG + 年月日 + 4位序号
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        String prefix = "CG" + dateStr;
        
        String maxOrderNo = getMaxOrderNo();
        int sequence = 1;
        
        if (maxOrderNo != null && maxOrderNo.startsWith(prefix)) {
            try {
                // 提取序号部分
                String sequenceStr = maxOrderNo.substring(prefix.length());
                sequence = Integer.parseInt(sequenceStr) + 1;
            } catch (Exception e) {
                log.error("生成订单编号异常", e);
            }
        }
        
        // 格式化序号为4位
        return prefix + String.format("%04d", sequence);
    }
    
    @Override
    public Map<String, Object> getProductSalesOrderSummary(ProductSalesOrderPageVO productSalesOrderPageVO) {
        log.info("开始获取订单汇总信息，查询条件: {}", productSalesOrderPageVO);
        
        // 创建返回结果
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 查询符合条件的订单总数
            Long totalOrders = baseMapper.countProductSalesOrder(productSalesOrderPageVO);
            result.put("totalOrders", totalOrders);
            
            // 查询符合条件的订单总销售额、总成本、总利润
            Map<String, BigDecimal> amountSummary = baseMapper.sumProductSalesOrderAmount(productSalesOrderPageVO);
            if(amountSummary == null){
                // 返回空结果
                result.put("totalOrders", 0);
                result.put("totalAmount", BigDecimal.ZERO);
                result.put("totalCost", BigDecimal.ZERO);
                result.put("totalProfit", BigDecimal.ZERO);
                result.put("profitRate", BigDecimal.ZERO);
                return result;
            }
            
            BigDecimal totalAmount = amountSummary.get("totalAmount") != null ? amountSummary.get("totalAmount") : BigDecimal.ZERO;
            BigDecimal totalCost = amountSummary.get("totalCost") != null ? amountSummary.get("totalCost") : BigDecimal.ZERO;
            BigDecimal totalProfit = amountSummary.get("totalProfit") != null ? amountSummary.get("totalProfit") : BigDecimal.ZERO;
            
            result.put("totalAmount", totalAmount);
            result.put("totalCost", totalCost);
            result.put("totalProfit", totalProfit);
            
            // 计算利润率
            BigDecimal profitRate = BigDecimal.ZERO;
            if (totalAmount.compareTo(BigDecimal.ZERO) > 0) {
                profitRate = totalProfit.multiply(new BigDecimal("100")).divide(totalAmount, 2, BigDecimal.ROUND_HALF_UP);
            }
            result.put("profitRate", profitRate);
            
            log.info("订单汇总信息获取成功: 订单总数={}, 总销售额={}, 总成本={}, 总利润={}, 利润率={}%",
                    totalOrders, totalAmount, totalCost, totalProfit, profitRate);
            
            return result;
        } catch (Exception e) {
            log.error("获取订单汇总信息失败", e);
            // 返回空结果
            result.put("totalOrders", 0);
            result.put("totalAmount", BigDecimal.ZERO);
            result.put("totalCost", BigDecimal.ZERO);
            result.put("totalProfit", BigDecimal.ZERO);
            result.put("profitRate", BigDecimal.ZERO);
            return result;
        }
    }
    
    /**
     * 计算订单金额
     *
     * @param productSalesOrderVO 订单信息及明细
     */
    private void calculateAmount(ProductSalesOrderVO productSalesOrderVO) {
        // 检查是否已经设置了销售总额、成本汇总和利润值
        boolean hasTotalAmount = productSalesOrderVO.getTotalAmount() != null && productSalesOrderVO.getTotalAmount().compareTo(BigDecimal.ZERO) > 0;
        boolean hasTotalCost = productSalesOrderVO.getTotalCost() != null && productSalesOrderVO.getTotalCost().compareTo(BigDecimal.ZERO) > 0;
        boolean hasProfit = productSalesOrderVO.getProfit() != null;
        
        // 如果前端没有传递销售总额或成本汇总，则从明细中计算
        if (!hasTotalAmount || !hasTotalCost) {
            List<ProductSalesOrderDetail> detailList = productSalesOrderVO.getProductSalesOrderDetailList();
            if (detailList != null && !detailList.isEmpty()) {
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal totalCost = BigDecimal.ZERO;
        
        for (ProductSalesOrderDetail detail : detailList) {
            // 计算明细金额
            if (detail.getUnitPrice() != null && detail.getQuantity() != null) {
                BigDecimal amount = detail.getUnitPrice().multiply(new BigDecimal(detail.getQuantity()));
                detail.setAmount(amount);
                totalAmount = totalAmount.add(amount);
            }
            
            // 累计成本
            if (detail.getCost() != null) {
                totalCost = totalCost.add(detail.getCost());
            }
        }
        
                // 只有在前端没有设置的情况下才从明细计算
                if (!hasTotalAmount) {
        productSalesOrderVO.setTotalAmount(totalAmount);
                }
                
                if (!hasTotalCost) {
                    productSalesOrderVO.setTotalCost(totalCost);
                }
            }
        }
        
        // 确保总金额和成本汇总不为null
        if (productSalesOrderVO.getTotalAmount() == null) {
            productSalesOrderVO.setTotalAmount(BigDecimal.ZERO);
        }
        
        if (productSalesOrderVO.getTotalCost() == null) {
            productSalesOrderVO.setTotalCost(BigDecimal.ZERO);
        }
        
        // 如果前端没有传递利润值，则计算利润 = 销售总额 - 成本汇总
        if (!hasProfit) {
            BigDecimal profit = productSalesOrderVO.getTotalAmount().subtract(productSalesOrderVO.getTotalCost());
            productSalesOrderVO.setProfit(profit);
        }
        
        // 确保预付款正确设置
        BigDecimal prepayment = productSalesOrderVO.getPrepayment();
        if (prepayment == null) {
            prepayment = BigDecimal.ZERO;
            productSalesOrderVO.setPrepayment(prepayment);
        }
        
        // 确保已付款金额正确设置
        BigDecimal paidAmount = productSalesOrderVO.getPaidAmount();
        if (paidAmount == null) {
            // 如果没有设置已付款金额，则使用预付款金额
            paidAmount = prepayment;
            productSalesOrderVO.setPaidAmount(paidAmount);
        }
        
        // 计算未付款金额 = 总金额 - 已付款金额
        BigDecimal totalAmount = productSalesOrderVO.getTotalAmount();
        BigDecimal unpaidAmount = totalAmount.subtract(paidAmount);
        productSalesOrderVO.setUnpaidAmount(unpaidAmount);
        
        // 设置付款状态
        if (paidAmount.compareTo(BigDecimal.ZERO) == 0) {
            // 未付款
            productSalesOrderVO.setPayStatus(0);
        } else if (paidAmount.compareTo(totalAmount) >= 0) {
            // 已付清
            productSalesOrderVO.setPayStatus(2);
        } else {
            // 部分付款
            productSalesOrderVO.setPayStatus(1);
        }
    }
    
    /**
     * 更新订单的已付款金额和付款状态
     * @param order 订单对象
     */
    private void updateOrderPaidAmount(ProductSalesOrder order) {
        if (order == null || StringUtils.isBlank(order.getId())) {
            return;
        }
        
        log.info("更新订单[{}]的付款金额和状态", order.getOrderNo());
        
        // 查询订单关联的所有交易记录
        List<ProductSalesOrderTransaction> transactions = productSalesOrderTransactionService.getTransactionListByOrderId(order.getId());
        if (transactions == null || transactions.isEmpty()) {
            log.info("订单[{}]没有关联的交易记录", order.getOrderNo());
            return;
        }
        
        // 计算已付款金额
        BigDecimal paidAmount = BigDecimal.ZERO;
        for (ProductSalesOrderTransaction transaction : transactions) {
            if (transaction.getAmount() != null) {
                // 退款类型的交易需要减去金额
                if (transaction.getTransactionType() != null && transaction.getTransactionType() == 4) {
                    paidAmount = paidAmount.subtract(transaction.getAmount());
                } else {
                    paidAmount = paidAmount.add(transaction.getAmount());
                }
            }
        }
        
        // 确保已付款金额不小于0
        if (paidAmount.compareTo(BigDecimal.ZERO) < 0) {
            paidAmount = BigDecimal.ZERO;
        }
        
        // 更新订单的已付款金额
        order.setPaidAmount(paidAmount);
        
        // 计算未付款金额
        BigDecimal totalAmount = order.getTotalAmount() != null ? order.getTotalAmount() : BigDecimal.ZERO;
        BigDecimal unpaidAmount = totalAmount.subtract(paidAmount);
        
        // 确保未付款金额不小于0
        if (unpaidAmount.compareTo(BigDecimal.ZERO) < 0) {
            unpaidAmount = BigDecimal.ZERO;
        }
        
        order.setUnpaidAmount(unpaidAmount);
        
        // 更新付款状态
        if (paidAmount.compareTo(BigDecimal.ZERO) <= 0) {
            // 未付款
            order.setPayStatus(0);
        } else if (unpaidAmount.compareTo(BigDecimal.ZERO) <= 0) {
            // 已付清
            order.setPayStatus(2);
        } else {
            // 部分付款
            order.setPayStatus(1);
        }
        
        log.info("订单[{}]更新付款信息：已付款={}, 未付款={}, 付款状态={}", 
                order.getOrderNo(), paidAmount, unpaidAmount, order.getPayStatus());
        
        // 更新订单
        updateById(order);
    }
    
    /**
     * 根据交易类型设置默认的交易描述
     * @param transaction 交易记录对象
     */
    private void setDefaultTransactionDescription(ProductSalesOrderTransaction transaction) {
        if (transaction == null || transaction.getTransactionType() == null) {
            return;
        }
        
        switch (transaction.getTransactionType()) {
            case 1:
                transaction.setDescription("订单预付款");
                break;
            case 2:
                transaction.setDescription("订单尾款");
                break;
            case 3:
                transaction.setDescription("订单全额付款");
                break;
            case 4:
                transaction.setDescription("订单退款");
                break;
            default:
                transaction.setDescription("订单交易");
        }
    }

    @Override
    public IPage<ProductSalesOrderVO> pageApprovedOrders(Page<ProductSalesOrderVO> page, ProductSalesOrder order) {
        return baseMapper.pageApprovedOrders(page, order);
    }
    
    @Override
    public ProductSalesOrderVO getOrderDetail(String id) {
        if (StringUtils.isBlank(id)) {
            throw new JeecgBootException("订单ID不能为空");
        }
        
        // 获取订单基本信息
        ProductSalesOrderVO orderVO = this.baseMapper.getOrderById(id);
        if (orderVO == null) {
            throw new JeecgBootException("未找到对应订单");
        }
        
        // 获取订单明细
        List<ProductSalesOrderDetail> detailList = orderDetailMapper.getDetailListByOrderId(id);
        orderVO.setProductSalesOrderDetailList(detailList);
        
        // 检查是否有设计文件
        DesignFile designFile = designFileService.getByOrderId(id);
        if (designFile != null) {
            orderVO.setHasSummaryFile(StringUtils.isNotBlank(designFile.getSummaryFilePath()));
            orderVO.setHasOptimizationFile(StringUtils.isNotBlank(designFile.getOptimizationFilePath()));
        } else {
            orderVO.setHasSummaryFile(false);
            orderVO.setHasOptimizationFile(false);
        }
        
        return orderVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSummaryFile(String orderId) {
        try {
            log.info("删除订单汇总单文件, orderId={}", orderId);
            
            // 先查询订单信息
            ProductSalesOrder order = getById(orderId);
            if (order == null) {
                log.error("订单不存在, orderId={}", orderId);
                return false;
            }
            
            // 查询设计文件
            DesignFile designFile = designFileService.getByOrderId(orderId);
            if (designFile == null) {
                log.warn("设计文件不存在, orderId={}", orderId);
                return true; // 如果没有设计文件，认为删除成功
            }
            
            // 清空汇总单文件路径
            designFile.setSummaryFilePath(null);
            
            // 更新设计文件
            boolean result = designFileService.updateById(designFile);
            //删除下属表数据
            List<Object> idList = orderDetailMapper.selectObjs(new QueryWrapper<ProductSalesOrderDetail>()
                    .select("id")
                    .eq("order_id", orderId));
            //删除配件表
            idList.forEach(id -> {
                accessoriesTableService.deleteByDetailId(id.toString());
                glassSizeTableService.deleteByDetailId(id.toString());
                profileSizeTableService.deleteByDetailId(id.toString());
            });

            log.info("删除订单汇总单文件 {}, orderId={}", result ? "成功" : "失败", orderId);
            return result;
        } catch (Exception e) {
            log.error("删除订单汇总单文件出错, orderId={}", orderId, e);
            throw new JeecgBootException("删除订单汇总单文件失败: " + e.getMessage());
        }
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOptimizationFile(String orderId) {
        try {
            log.info("删除订单优化单文件, orderId={}", orderId);

            // 先查询订单信息
            ProductSalesOrder order = getById(orderId);
            if (order == null) {
                log.error("订单不存在, orderId={}", orderId);
                return false;
            }

            // 查询设计文件
            DesignFile designFile = designFileService.getByOrderId(orderId);
            if (designFile == null) {
                log.warn("设计文件不存在, orderId={}", orderId);
                return true; // 如果没有设计文件，认为删除成功
            }

            // 清空优化单文件路径
            designFile.setOptimizationFilePath(null);

            // 更新设计文件
            boolean result = designFileService.updateById(designFile);

            //删除领料表和切割详情表数据
            xingeProfileMaterialService.deleteByOrderId(orderId);
            xingeProfileCutDetailService.deleteByOrderId(orderId);
            //长风优化软件
            cfProfileMaterialService.deleteByOrderId(orderId);
            cfProfileCutDetailService.deleteByOrderId(orderId);
            cfProfileWorkDetailService.deleteByOrderId(orderId);

            log.info("删除订单优化单文件 {}, orderId={}", result ? "成功" : "失败", orderId);
            return result;
        } catch (Exception e) {
            log.error("删除订单优化单文件出错, orderId={}", orderId, e);
            throw new JeecgBootException("删除订单优化单文件失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSummaryOrderStatus(ProductSalesOrder order,String userId, String userName) {
        // 更新订单状态为已上传汇总单(状态码2)
        Integer oldStatus = order.getStatus();
        if (oldStatus != null && oldStatus == 1) {
            order.setStatus(2);
            this.updateById(order);

            // 记录订单进度
            try {
                // 记录订单状态变更
                ProductSalesOrderProgress progress = new ProductSalesOrderProgress();
                progress.setOrderId(order.getId());
                progress.setOldStatus(1);
                progress.setNewStatus(2);
                progress.setChangeTime(new Date());
                progress.setOperatorId(userId);
                progress.setOperatorName(userName);
                progress.setChangeReason("上传汇总单");
                productSalesOrderProgressService.save(progress);
            } catch (Exception e) {
                // 进度记录失败不影响主流程
                log.error("记录订单进度失败", e);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRequisitionInfo(String orderIds,ArrayList<String> orderNoList ) {
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (loginUser == null) {
            log.error("未获取到当前登录用户信息，无法生成领料单");
            return;
        }

        try {
            // 创建领料单主表记录
            WmsRequisitionVO requisition = new WmsRequisitionVO();
            
            // 为主键ID生成唯一值
            String requisitionId = UUIDGenerator.generate();
            requisition.setId(requisitionId);
            
            // 生成领料单号：LLD + 年月日 + 6位流水号 + 4位随机数
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String dateStr = sdf.format(new Date());
            
            // 查询当天最大领料单号
            QueryWrapper<WmsRequisitionVO> queryWrapper = new QueryWrapper<>();
            queryWrapper.likeRight("requisition_no", "LLD" + dateStr)
                        .orderByDesc("requisition_no")
                        .last("limit 1");
            WmsRequisitionVO latestRequisition = wmsRequisitionVOMapper.selectOne(queryWrapper);
            
            // 生成流水号
            int sequenceNo = 1;
            if (latestRequisition != null && latestRequisition.getRequisitionNo() != null) {
                String latestNo = latestRequisition.getRequisitionNo();
                if (latestNo.length() >= 18) {
                    try {
                        // 提取流水号部分，位置为LLD + 8位日期后的6位
                        String seqStr = latestNo.substring(11, 17);
                        sequenceNo = Integer.parseInt(seqStr) + 1;
                    } catch (Exception e) {
                        log.warn("解析最近领料单号流水号失败，使用默认值1", e);
                    }
                }
            }
            
            // 生成4位随机数
            int randomNum = (int) (Math.random() * 10000);
            
            // 组装领料单号：LLD + 日期(8位) + 流水号(6位) + 随机数(4位)
            String requisitionNo = String.format("LLD%s%06d%04d", dateStr, sequenceNo, randomNum);
            
            // 再次检查是否重复
            queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("requisition_no", requisitionNo);
            WmsRequisitionVO existRequisition = wmsRequisitionVOMapper.selectOne(queryWrapper);
            
            // 如果重复，增加随机数再试
            int retryCount = 0;
            while (existRequisition != null && retryCount < 10) {
                randomNum = (int) (Math.random() * 10000);
                requisitionNo = String.format("LLD%s%06d%04d", dateStr, sequenceNo, randomNum);
                queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("requisition_no", requisitionNo);
                existRequisition = wmsRequisitionVOMapper.selectOne(queryWrapper);
                retryCount++;
            }
            
            // 如果仍然重复，使用更具唯一性的UUID最后12位
            if (existRequisition != null) {
                requisitionNo = String.format("LLD%s%s", dateStr, UUIDGenerator.generate().substring(24));
            }
            
            requisition.setRequisitionNo(requisitionNo);
            
            // 设置基本信息
            requisition.setOrderId(orderIds);
            String orderNo = String.join(",", orderNoList);
            requisition.setOrderNo(orderNo);
            ProductSalesOrder order = this.getById(orderIds.split(",")[0]);
            requisition.setOptimizationSoftwareType(order.getOptimizationSoftwareType());
            requisition.setStatus(0); // 待审核
            requisition.setCreateBy(loginUser.getUsername());
            requisition.setCreateTime(new Date());
            
            // 保存领料单主表
            wmsRequisitionVOMapper.insert(requisition);
            
            log.info("已创建领料单主表记录，ID: {}, 领料单号: {}", requisitionId, requisitionNo);
            
            List<WmsRequisitionProfileVO> profileList = new ArrayList<>();
            List<WmsRequisitionAccessoryVO> accessoryList = new ArrayList<>();
            
            // 根据优化软件类型获取型材和配件数据
            Integer optimizationType = order.getOptimizationSoftwareType();
            //合单优化ID列表
            String optimizationIds = "";
            
            if (Integer.valueOf(0).equals(optimizationType)) {
                // 长风类型 - 获取型材和配件数据
                List<CfProfileMaterial> cfProfiles = cfProfileMaterialService.getByOrderId(order.getId());
                
                if (cfProfiles != null && !cfProfiles.isEmpty()) {
                    log.info("订单[{}]的长风型材数据共{}条", order.getOrderNo(), cfProfiles.size());
                    
                    // 使用Map来汇总相同型材，key为"型材编号+型材名称+颜色+长度+宽度+高度"的组合
                    Map<String, WmsRequisitionProfileVO> profileSummaryMap = new HashMap<>();
                    
                    for (CfProfileMaterial cfProfile : cfProfiles) {
                        // 构建型材唯一标识
                        String profileKey = cfProfile.getProfileCode() + "_" + cfProfile.getProfileName() + "_" + 
                                          cfProfile.getColor() + "_" + cfProfile.getLength() + "_" + 
                                          cfProfile.getWidth() + "_" + cfProfile.getHeight();
                        
                        WmsRequisitionProfileVO profileData;
                        
                        if (profileSummaryMap.containsKey(profileKey)) {
                            // 如果已经存在相同型材，则累加数量
                            profileData = profileSummaryMap.get(profileKey);
                            Integer quantity = profileData.getQuantity();
                            profileData.setQuantity(quantity + cfProfile.getQuantity());
                            // 如果有重量，也累加重量
                            if (profileData.getWeight() != null && cfProfile.getWeight() != null) {
                                BigDecimal weight = profileData.getWeight();
                                profileData.setWeight(weight.add(BigDecimal.valueOf(cfProfile.getWeight())));
                            }
                        } else {
                            // 创建新型材记录
                            profileData = new WmsRequisitionProfileVO();
                            profileData.setId(UUIDGenerator.generate()); // 为明细设置唯一ID
                            profileData.setRequisitionId(requisitionId);
                            profileData.setProfileCode(cfProfile.getProfileCode());
                            profileData.setProfileName(cfProfile.getProfileName());
                            profileData.setColor(cfProfile.getColor());
                            profileData.setLength(new BigDecimal(cfProfile.getLength()));
                            profileData.setWidth(new BigDecimal(cfProfile.getWidth()));
                            profileData.setHeight(new BigDecimal(cfProfile.getHeight()));
                            profileData.setQuantity(cfProfile.getQuantity());
                            if (cfProfile.getWeight() != null) {
                                profileData.setWeight(new BigDecimal(cfProfile.getWeight()));
                            }
                            profileData.setStatus(0); // 设置状态为未领料
                            profileData.setCreateBy(loginUser.getUsername());
                            profileData.setCreateTime(new Date());
                            
                            // 添加到汇总Map
                            profileSummaryMap.put(profileKey, profileData);
                        }
                    }
                    
                    // 将汇总后的型材数据添加到profileList
                    profileList.addAll(profileSummaryMap.values());
                    log.info("订单[{}]汇总后的长风型材数据共{}条", order.getOrderNo(), profileList.size());
                }
                
                // 查询订单明细
                List<ProductSalesOrderDetail> details = productSalesOrderDetailService.getDetailListByOrderId(order.getId());
                if (details != null && !details.isEmpty()) {
                    // 用于汇总相同配件
                    Map<String, WmsRequisitionAccessoryVO> accessorySummaryMap = new HashMap<>();
                    
                    for (ProductSalesOrderDetail detail : details) {
                        // 获取配件数据
                        List<CfAccessoriesTable> cfAccessories = cfAccessoriesTableService.getListByDetailId(detail.getId());
                        
                        if (cfAccessories != null && !cfAccessories.isEmpty()) {
                            log.info("订单[{}]明细[{}]的长风配件数据共{}条", order.getOrderNo(), detail.getId(), cfAccessories.size());
                            
                            for (CfAccessoriesTable cfAccessory : cfAccessories) {
                                // 构建配件唯一标识
                                String accessoryKey = cfAccessory.getAccessoryCode() + "_" + cfAccessory.getAccessoryName();
                                
                                WmsRequisitionAccessoryVO accessoryData;
                                
                                if (accessorySummaryMap.containsKey(accessoryKey)) {
                                    // 如果已经存在相同配件，则累加数量
                                    accessoryData = accessorySummaryMap.get(accessoryKey);
                                    Integer quantity = accessoryData.getQuantity();
                                    accessoryData.setQuantity(quantity + cfAccessory.getQuantity());
                                } else {
                                    // 创建新配件记录
                                    accessoryData = new WmsRequisitionAccessoryVO();
                                    accessoryData.setId(UUIDGenerator.generate()); // 为明细设置唯一ID
                                    accessoryData.setRequisitionId(requisitionId);
                                    accessoryData.setAccessoryCode(cfAccessory.getAccessoryCode());
                                    accessoryData.setAccessoryName(cfAccessory.getAccessoryName());
                                    accessoryData.setSpecification(cfAccessory.getSpecification());
                                    accessoryData.setQuantity(cfAccessory.getQuantity());
                                    accessoryData.setUnit(cfAccessory.getUnit());
                                    accessoryData.setBrand(cfAccessory.getBrand());
                                    accessoryData.setStatus(0); // 设置状态为未领料
                                    accessoryData.setCreateBy(loginUser.getUsername());
                                    accessoryData.setCreateTime(new Date());
                                    
                                    // 添加到汇总Map
                                    accessorySummaryMap.put(accessoryKey, accessoryData);
                                }
                            }
                        }
                    }
                    
                    // 将汇总后的配件数据添加到accessoryList
                    accessoryList.addAll(accessorySummaryMap.values());
                    log.info("订单[{}]汇总后的长风配件数据共{}条", order.getOrderNo(), accessoryList.size());
                }
            }
            else if (Integer.valueOf(1).equals(optimizationType)) {
                // 新格尔类型 - 获取型材和配件数据
                List<XingeProfileMaterial> xingeProfiles = xingeProfileMaterialService.getByOrderId(orderIds);

                if (xingeProfiles != null && !xingeProfiles.isEmpty()) {
                    orderIds = xingeProfiles.get(0).getOrderId();
                    log.info("订单[{}]的新格尔型材数据共{}条", order.getOrderNo(), xingeProfiles.size());
                    
                    // 使用Map来汇总相同型材，key为"型材编号+型材名称+长度"的组合
                    Map<String, WmsRequisitionProfileVO> profileSummaryMap = new HashMap<>();
                    
                    for (XingeProfileMaterial xingeProfile : xingeProfiles) {
                        // 构建型材唯一标识
                        String profileKey = xingeProfile.getProfileCode() + "_" + xingeProfile.getProfileName() + "_" + xingeProfile.getLength();
                        
                        WmsRequisitionProfileVO profileData;
                        
                        if (profileSummaryMap.containsKey(profileKey)) {
                            // 如果已经存在相同型材，则累加数量
                            profileData = profileSummaryMap.get(profileKey);
                            Integer quantity = profileData.getQuantity();
                            profileData.setQuantity(quantity + xingeProfile.getQuantity());
                        } else {
                            // 创建新型材记录
                            profileData = new WmsRequisitionProfileVO();
                            profileData.setId(UUIDGenerator.generate()); // 为明细设置唯一ID
                            profileData.setRequisitionId(requisitionId);
                            profileData.setProfileCode(xingeProfile.getProfileCode());
                            profileData.setProfileName(xingeProfile.getProfileName());
                            profileData.setLength(new BigDecimal(xingeProfile.getLength()));
                            profileData.setQuantity(xingeProfile.getQuantity());
                            profileData.setColor(xingeProfile.getColor());
                            profileData.setStatus(0); // 设置状态为未领料
                            profileData.setCreateBy(loginUser.getUsername());
                            profileData.setCreateTime(new Date());
                            
                            // 添加到汇总Map
                            profileSummaryMap.put(profileKey, profileData);
                        }
                    }
                    
                    // 将汇总后的型材数据添加到profileList
                    profileList.addAll(profileSummaryMap.values());
                    log.info("订单[{}]汇总后的新格尔型材数据共{}条", order.getOrderNo(), profileList.size());
                }else {
                    throw new JeecgBootException("订单[" + order.getOrderNo() + "]的优化单类型为【新格尔】，但未找到对应的型材数据");
                }
                optimizationIds = xingeProfiles.get(0).getOrderId();
                // 查询订单明细
                List<ProductSalesOrderDetail> details = productSalesOrderDetailService.getDetailListByOrderIds(optimizationIds);
                if (details != null && !details.isEmpty()) {
                    // 用于汇总相同配件
                    Map<String, WmsRequisitionAccessoryVO> accessorySummaryMap = new HashMap<>();
                    
                    for (ProductSalesOrderDetail detail : details) {
                        // 获取配件数据
                        List<XgeAccessoriesTable> xgeAccessories = accessoriesTableService.getListByDetailId(detail.getId());
                        
                        if (xgeAccessories != null && !xgeAccessories.isEmpty()) {
                            log.info("订单[{}]明细[{}]的新格尔配件数据共{}条", order.getOrderNo(), detail.getId(), xgeAccessories.size());
                            
                            for (XgeAccessoriesTable xgeAccessory : xgeAccessories) {
                                // 构建配件唯一标识
                                String accessoryKey = xgeAccessory.getAccessoryCode() + "_" + xgeAccessory.getAccessoryName();
                                
                                WmsRequisitionAccessoryVO accessoryData;
                                
                                if (accessorySummaryMap.containsKey(accessoryKey)) {
                                    // 如果已经存在相同配件，则累加数量
                                    accessoryData = accessorySummaryMap.get(accessoryKey);
                                    Double lengthQuantity = Double.parseDouble(accessoryData.getLengthQuantity());
                                    double value = lengthQuantity + Double.parseDouble(xgeAccessory.getLengthQuantity());
                                    //value 保留两位小数
                                    value = Math.round(value * 100) / 100.0;
                                    String str = String.valueOf(value);
                                    accessoryData.setLengthQuantity(str);
                                } else {
                                    // 创建新配件记录
                                    accessoryData = new WmsRequisitionAccessoryVO();
                                    accessoryData.setId(UUIDGenerator.generate()); // 为明细设置唯一ID
                                    accessoryData.setRequisitionId(requisitionId);
                                    accessoryData.setAccessoryCode(xgeAccessory.getAccessoryCode());
                                    accessoryData.setAccessoryName(xgeAccessory.getAccessoryName());
                                    accessoryData.setLengthQuantity(xgeAccessory.getLengthQuantity());
                                    accessoryData.setUnit(xgeAccessory.getUnit());
                                    accessoryData.setStatus(0); // 设置状态为未领料
                                    accessoryData.setCreateBy(loginUser.getUsername());
                                    accessoryData.setCreateTime(new Date());
                                    
                                    // 添加到汇总Map
                                    accessorySummaryMap.put(accessoryKey, accessoryData);
                                }
                            }
                        }
                    }
                    
                    // 将汇总后的配件数据添加到accessoryList
                    accessoryList.addAll(accessorySummaryMap.values());
                    log.info("订单[{}]汇总后的新格尔配件数据共{}条", order.getOrderNo(), accessoryList.size());
                }
            } else {
                log.error("订单[{}]的优化软件类型[{}]无效", order.getOrderNo(), optimizationType);
                return;
            }
            
            // 批量保存型材数据
            if (!profileList.isEmpty()) {
                for (WmsRequisitionProfileVO profile : profileList) {
                    wmsRequisitionProfileVOMapper.insert(profile);
                }
                log.info("成功保存{}条型材领料数据", profileList.size());
            }
            
            // 批量保存配件数据
            if (!accessoryList.isEmpty()) {
                for (WmsRequisitionAccessoryVO accessory : accessoryList) {
                    wmsRequisitionAccessoryVOMapper.insert(accessory);
                }
                log.info("成功保存{}条配件领料数据", accessoryList.size());
            }
            
            // 如果没有型材和配件数据，则不创建领料单
            if (profileList.isEmpty() && accessoryList.isEmpty()) {
                log.warn("订单[{}]没有型材和配件数据，删除已创建的领料单", order.getOrderNo());
                wmsRequisitionVOMapper.deleteById(requisitionId);
                return;
            }
            
            log.info("订单[{}]成功生成领料单[{}]", order.getOrderNo(), requisitionNo);


            //生成领料单后，需要把合单优化的相关订单状态改为领料单待审核
            // 更新订单状态为 已上传优化单-待提交审核3 -> 领料单待审核5
            String[] orderIdArray = optimizationIds.split(",");
            for (String id : orderIdArray){
                this.updateOrderStatus(id, 3, 5, loginUser.getId(), "设计人员提交审核");
            }
            
            // 发布领料单出库事件，通知WMS模块创建对应的出库单
            try {
                // 构建出库事件
                RequisitionOutboundEvent event = new RequisitionOutboundEvent()
                    .setRequisitionId(requisitionId)
                    .setRequisitionNo(requisitionNo)
                    .setOrderId(orderIds)
                    .setOrderNo(orderNo)
                    .setWarehouseId("")
                    .setTenantId(loginUser.getRelTenantIds())
                    .setCreateBy(loginUser.getUsername());
                
                // 转换型材数据
                if (profileList != null && !profileList.isEmpty()) {
                    List<RequisitionOutboundEvent.ProfileItem> eventProfileList = new ArrayList<>();
                    for (WmsRequisitionProfileVO profile : profileList) {
                        RequisitionOutboundEvent.ProfileItem item = new RequisitionOutboundEvent.ProfileItem()
                            .setProfileCode(profile.getProfileCode())
                            .setProfileName(profile.getProfileName())
                            .setColor(profile.getColor())
                            .setLength(profile.getLength())
                            .setWidth(profile.getWidth())
                            .setHeight(profile.getHeight())
                            .setQuantity(profile.getQuantity())
                            .setWeight(profile.getWeight());
                        eventProfileList.add(item);
                    }
                    event.setProfileList(eventProfileList);
                }
                
                // 转换配件数据
                if (accessoryList != null && !accessoryList.isEmpty()) {
                    List<RequisitionOutboundEvent.AccessoryItem> eventAccessoryList = new ArrayList<>();
                    for (WmsRequisitionAccessoryVO accessory : accessoryList) {
                        RequisitionOutboundEvent.AccessoryItem item = new RequisitionOutboundEvent.AccessoryItem()
                            .setAccessoryCode(accessory.getAccessoryCode())
                            .setAccessoryName(accessory.getAccessoryName())
                            .setSpecification(accessory.getSpecification())
                            .setQuantity(accessory.getQuantity())
                            .setLengthQuantity(accessory.getLengthQuantity())
                            .setUnit(accessory.getUnit())
                            .setBrand(accessory.getBrand());
                        eventAccessoryList.add(item);
                    }
                    event.setAccessoryList(eventAccessoryList);
                }
                
                // 发布事件
                eventPublisher.publishRequisitionOutboundEvent(event);
                log.info("订单[{}]成功发布领料单出库事件", order.getOrderNo());
                
            } catch (Exception e) {
                log.error("发布领料单出库事件异常，但领料单已创建成功", e);
                // 事件发布失败不影响领料单的创建，只记录日志
            }
            
        } catch (Exception e) {
            log.error("生成领料单异常", e);
            throw new JeecgBootException("生成领料单失败: " + e.getMessage());
        }
    }
    
    @Override
    public IPage<ProductSalesOrderVO> getOrderListWithoutYuLiaoRuku() {
        // 创建分页对象，不分页，查询所有符合条件的数据
        Page<ProductSalesOrderVO> page = new Page<>(1, 1000);
        
        // 调用Mapper查询未生成余料入库单的订单列表
        IPage<ProductSalesOrderVO> result = baseMapper.getOrderListWithoutYuLiaoRuku(page);
        
        log.info("查询未生成余料入库单的订单列表，共{}条记录", result.getRecords().size());
        
        return result;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BigDecimal calculateAndUpdateOrderTotalCost(String orderId) {
        try {
            log.info("开始计算订单总成本, orderId={}", orderId);
            
            // 获取订单信息
            ProductSalesOrder order = this.getById(orderId);
            if (order == null) {
                log.error("订单不存在, orderId={}", orderId);
                throw new JeecgBootException("订单不存在");
            }
            
            BigDecimal totalCost = BigDecimal.ZERO;
            
            // 根据优化软件类型计算成本
            if (order.getOptimizationSoftwareType() == 1) {
                // 新格尔软件类型：计算型材成本 + 配件成本
                totalCost = calculateXgeCost(orderId);
            } else if (order.getOptimizationSoftwareType() == 0) {
                // 长风软件类型：计算型材成本 + 配件成本
                totalCost = calculateCfCost(orderId);
            }
            
            // 更新订单总成本
            order.setTotalCost(totalCost);
            order.setProfit(order.getTotalAmount().subtract(totalCost));
            this.updateById(order);
            
            log.info("订单总成本计算完成, orderId={}, totalCost={}", orderId, totalCost);
            return totalCost;
            
        } catch (Exception e) {
            log.error("计算订单总成本失败, orderId={}", orderId, e);
            throw new JeecgBootException("计算订单总成本失败: " + e.getMessage());
        }
    }
    
    /**
     * 计算新格尔软件类型订单成本
     */
    private BigDecimal calculateXgeCost(String orderId) {
//        BigDecimal profileCost = BigDecimal.ZERO;
//        BigDecimal accessoryCost = BigDecimal.ZERO;
//
//        // 计算型材成本
//        List<XingeProfileMaterial> profileList = xingeProfileMaterialService.list(
//            new LambdaQueryWrapper<XingeProfileMaterial>()
//                .eq(XingeProfileMaterial::getOrderId, orderId)
//        );
//
//        for (XingeProfileMaterial profile : profileList) {
//
//            if (profile.getLength() != null && profile.getQuantity() != null && profile.getUnitCost() != null && profile.getMaterialLength() != null) {
//                BigDecimal unitCostPerMm = profile.getUnitCost().divide(profile.getMaterialLength(), 6, BigDecimal.ROUND_HALF_UP);
//                BigDecimal cost = profile.getLength().multiply(unitCostPerMm).multiply(profile.getQuantity());
//                profileCost = profileCost.add(cost);
//            }
//        }
//
//        // 计算配件成本
//        List<XgeAccessoriesTable> accessoryList = xgeAccessoriesTableService.list(
//            new LambdaQueryWrapper<XgeAccessoriesTable>()
//                .eq(XgeAccessoriesTable::getOrderId, orderId)
//        );
//
//        for (XgeAccessoriesTable accessory : accessoryList) {
//            if (accessory.getQuantity() != null && accessory.getUnitCost() != null) {
//                BigDecimal cost = accessory.getQuantity().multiply(accessory.getUnitCost());
//                accessoryCost = accessoryCost.add(cost);
//            }
//        }
//
//        return profileCost.add(accessoryCost);
        return new BigDecimal(0);
    }

    /**
     * 计算长风软件类型订单成本
     */
    private BigDecimal calculateCfCost(String orderId) {
//        BigDecimal profileCost = BigDecimal.ZERO;
//        BigDecimal accessoryCost = BigDecimal.ZERO;
//
//        // 计算型材成本
//        List<CfProfileMaterial> profileList = cfProfileMaterialService.list(
//            new LambdaQueryWrapper<CfProfileMaterial>()
//                .eq(CfProfileMaterial::getOrderId, orderId)
//        );
//
//        for (CfProfileMaterial profile : profileList) {
//            if (profile.getLength() != null && profile.getQuantity() != null && profile.getUnitCost() != null && profile.getMaterialLength() != null) {
//                BigDecimal unitCostPerMm = profile.getUnitCost().divide(profile.getMaterialLength(), 6, BigDecimal.ROUND_HALF_UP);
//                BigDecimal cost = profile.getLength().multiply(unitCostPerMm).multiply(profile.getQuantity());
//                profileCost = profileCost.add(cost);
//            }
//        }
//
//        // 计算配件成本
//        List<CfAccessoriesTable> accessoryList = cfAccessoriesTableService.list(
//            new LambdaQueryWrapper<CfAccessoriesTable>()
//                .eq(CfAccessoriesTable::getOrderId, orderId)
//        );
//
//        for (CfAccessoriesTable accessory : accessoryList) {
//            if (accessory.getQuantity() != null && accessory.getUnitCost() != null) {
//                BigDecimal cost = accessory.getQuantity().multiply(accessory.getUnitCost());
//                accessoryCost = accessoryCost.add(cost);
//            }
//        }
//
//        return profileCost.add(accessoryCost);
        return new BigDecimal(0);
    }
}